//
//  WXPLoginVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/24.
//
//

#import "WXPLoginVC.h"
#import "WXPChooseSMSVerificWayView.h"
#import "WXPLoginAuthVC.h"
#import "UpdatePopUpWindowView.h"
#import "WXPAgreementDialogView.h"


@interface WXPLoginVC ()<UITextFieldDelegate, UITextViewDelegate>

@property (nonatomic, strong) UIView * viewBg;
@property (nonatomic, strong) UIImageView * imageLogo;
@property (nonatomic, strong) UIImageView * imageBg;
@property (nonatomic, strong) UILabel * labelTitle;
@property (nonatomic, strong) UIView * viewBack;
@property (nonatomic, strong) UILabel * labelAudioSendHint;
@property (nonatomic, strong) UIView * viewPhoneBack;
@property (nonatomic, strong) UILabel * labelPhoneArea;
@property (nonatomic, strong) UITextField * tfPhone;
@property (nonatomic, strong) UIView * viewCodeBack;
@property (nonatomic, strong) UITextField * tfCode;
@property (nonatomic, strong) UIButton * btnCode;
@property (nonatomic, strong) UILabel * labelTime;
@property (nonatomic, strong) UIButton * btnAudio;
@property (nonatomic, strong) UILabel * labelAudio;
@property (nonatomic, strong) UILabel * labelAudioTime;
@property (nonatomic, strong) UIImageView * imageAudio;
@property (nonatomic, strong) UIButton * btnLogin;
@property (nonatomic,   copy) NSString * strAgreement;
@property (nonatomic,   copy) NSString * strServicio;
@property (nonatomic,   copy) NSString * strPrivacidad;
@property (nonatomic, strong) UITextView * labelAgreement;
@property (nonatomic, strong) WXPChooseSMSVerificWayView * chooseSMSVerificWayView;
@property (nonatomic, strong) UpdatePopUpWindowView * updatePromptView;
@property (nonatomic, strong) WXPAgreementDialogView * viewAgreementDialog;

@property (nonatomic,   copy) NSString * startTime;

@end

@implementation WXPLoginVC

#pragma mark - lazy
- (UIView *)viewBg{
    if (!_viewBg) {
        _viewBg = [UIView new];
        _viewBg.backgroundColor = COLOR_PRIMARY;
        _viewBg.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT);
        _viewBg.leftTop = XY(0, 0);
    }
    return _viewBg;
}
- (UIImageView *)imageLogo{
    if (!_imageLogo) {
        _imageLogo = [UIImageView new];
        _imageLogo.widthHeight = XY(36, 36);
        _imageLogo.image = [UIImage imageNamed:@"icon-login-logo"];
        _imageLogo.leftTop = XY(30, [GlobalMethod getNavgationBarHeight]);
    }
    return _imageLogo;
}
- (UIImageView *)imageBg{
    if (!_imageBg) {
        _imageBg = [UIImageView new];
        _imageBg.widthHeight = XY(185, 185);
        _imageBg.image = [UIImage imageNamed:@"icon-login-bg"];
        _imageBg.rightTop = XY(SCREEN_WIDTH, self.imageLogo.top+10);
    }
    return _imageBg;
}
- (UILabel *)labelTitle{
    if (!_labelTitle) {
        _labelTitle = [UILabel new];
        _labelTitle.textColor = COLOR_BLACK;
        _labelTitle.numberOfLines = 0;
        _labelTitle.font = [UIFont fontWithName:@"PingFangSC-Medium" size:24.0];
        [_labelTitle fitTitle:@"Por favor inicie sesión\nprimero" variable:0];
    }
    return _labelTitle;
}
- (UIView *)viewBack{
    if (!_viewBack) {
        _viewBack = [UIView new];
        _viewBack.userInteractionEnabled = true;
        _viewBack.backgroundColor = COLOR_WHITE;
        _viewBack.widthHeight = XY(SCREEN_WIDTH, 0);
    }
    return _viewBack;
}
- (UILabel *)labelAudioSendHint{
    if (!_labelAudioSendHint) {
        _labelAudioSendHint = [UILabel new];
        [GlobalMethod setLabel:_labelAudioSendHint widthLimit:SCREEN_WIDTH-30-30 numLines:0 lineSpace:1 fontNum:12 textColor:COLOR_LIGHT_GRAY text:@""];
        _labelAudioSendHint.hidden = true;
    }
    return _labelAudioSendHint;
}
- (UIView *)viewPhoneBack{
    if (!_viewPhoneBack) {
        _viewPhoneBack = [UIView new];
        _viewPhoneBack.widthHeight = XY(SCREEN_WIDTH-30-30, Ratio(44));
        [GlobalMethod setRoundView:_viewPhoneBack color:COLOR_LINE numRound:16 width:1];
    }
    return _viewPhoneBack;
}
- (UILabel *)labelPhoneArea{
    if (!_labelPhoneArea) {
        _labelPhoneArea = [UILabel new];
        _labelPhoneArea.textAlignment = NSTextAlignmentCenter;
        _labelPhoneArea.backgroundColor = COLOR_BACKGROUND;
        _labelPhoneArea.widthHeight = XY(55, self.viewPhoneBack.height-12);
        [GlobalMethod setRoundView:_labelPhoneArea color:[UIColor clearColor] numRound:15 width:0];
        _labelPhoneArea.textColor = COLOR_BLACK;
        _labelPhoneArea.fontNum = 14;
        _labelPhoneArea.text = @"+52";
    }
    return _labelPhoneArea;
}
- (UITextField *)tfPhone{
    if (!_tfPhone) {
        _tfPhone = [UITextField new];
        _tfPhone.placeholder = @"Número de teléfono";
        _tfPhone.font = [UIFont systemFontOfSize:14];
        _tfPhone.textColor = COLOR_BLACK;
        _tfPhone.delegate = self;
        _tfPhone.borderStyle = UITextBorderStyleNone;
        _tfPhone.keyboardType = UIKeyboardTypePhonePad;
        _tfPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_tfPhone addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _tfPhone;
}
- (UIView *)viewCodeBack{
    if (!_viewCodeBack) {
        _viewCodeBack = [UIView new];
        _viewCodeBack.userInteractionEnabled = true;
        _viewCodeBack.widthHeight = XY(SCREEN_WIDTH-30-30, Ratio(44));
        [GlobalMethod setRoundView:_viewCodeBack color:COLOR_LINE numRound:16 width:1];
    }
    return _viewCodeBack;
}
- (UIButton *)btnCode{
    if (!_btnCode) {
        _btnCode = [UIButton new];
        _btnCode.titleLabel.fontNum = 14;
        [_btnCode setTitle:@"Conseguir código" forState:UIControlStateNormal];
        [_btnCode setTitleColor:COLOR_LIGHT_GRAY forState:UIControlStateNormal];
        _btnCode.userInteractionEnabled = false;
        [_btnCode sizeToFit];
        _btnCode.height = self.viewCodeBack.height;
        _btnCode.tag = 2;
        [_btnCode addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        _btnCode.rightCenterY = XY(self.viewCodeBack.width-19, self.viewCodeBack.height/2);
    }
    return _btnCode;
}
- (UITextField *)tfCode{
    if (_tfCode == nil) {
        _tfCode = [UITextField new];
        _tfCode.font = [UIFont systemFontOfSize:14];
        _tfCode.placeholder = @"Código de verificación";
        _tfCode.borderStyle = UITextBorderStyleNone;
        _tfCode.keyboardType = UIKeyboardTypePhonePad;
        _tfCode.backgroundColor = [UIColor clearColor];
        _tfCode.delegate = self;
        _tfCode.allowsEditingTextAttributes = false;
        [_tfCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _tfCode;
}
- (UILabel *)labelTime
{
    if (_labelTime == nil) {
        _labelTime = [UILabel new];
        _labelTime.fontNum = 14;
        _labelTime.textColor = COLOR_LIGHT_GRAY;
        [_labelTime fitTitle:@"60s" variable:0];
        _labelTime.hidden = true;
    }
    return  _labelTime;
}
- (UIButton *)btnAudio{
    if (!_btnAudio) {
        _btnAudio = [UIButton new];
        _btnAudio.widthHeight = XY(SCREEN_WIDTH-30-30, 46);
        _btnAudio.userInteractionEnabled = false;
        self.imageAudio.leftCenterY = XY(0, _btnAudio.height/2);
        [_btnAudio addSubview:self.imageAudio];
        self.labelAudio.leftCenterY = XY(self.imageAudio.right+5, self.imageAudio.centerY);
        [_btnAudio addSubview:self.labelAudio];
        self.labelAudioTime.leftCenterY = XY(self.labelAudio.left, self.imageAudio.centerY);
        [_btnAudio addSubview:self.labelAudioTime];
        _btnAudio.width = self.labelAudio.right+10;
        _btnAudio.tag = 3;
        [_btnAudio addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnAudio;
}
- (UIImageView *)imageAudio{
    if (!_imageAudio) {
        _imageAudio = [UIImageView new];
        _imageAudio.image = [UIImage imageNamed:@"icon-login-audio-unclick"];
        _imageAudio.widthHeight = XY(26, 26);
    }
    return _imageAudio;
}
- (UILabel *)labelAudio{
    if (!_labelAudio) {
        _labelAudio = [UILabel new];
        _labelAudio.textColor = COLOR_LIGHT_GRAY;
        _labelAudio.fontNum = 14;
        [_labelAudio fitTitle:@"liamame>" variable:0];
    }
    return _labelAudio;
}
- (UILabel *)labelAudioTime{
    if (!_labelAudioTime) {
        _labelAudioTime = [UILabel new];
        _labelAudioTime.textColor = COLOR_BLACK;
        _labelAudioTime.fontNum = 14;
        [_labelAudioTime fitTitle:@"60s" variable:0];
        _labelAudioTime.hidden = true;
    }
    return _labelAudioTime;
}
- (UIButton *)btnLogin{
    if (!_btnLogin) {
        _btnLogin = [UIButton new];
        _btnLogin.widthHeight = XY(SCREEN_WIDTH-30*2, BUTTON_HEIGHT);
        [GlobalMethod setRoundView:_btnLogin color:[UIColor clearColor] numRound:_btnLogin.height/2 width:0];
        _btnLogin.backgroundColor = [UIColor colorWithHexString:@"#F2F39C"];
        _btnLogin.userInteractionEnabled = false;
        _btnLogin.titleLabel.fontNum = 14;
        [_btnLogin setTitleColor:[UIColor colorWithHexString:@"#838380"] forState:UIControlStateNormal];
        [_btnLogin setTitle:@"Ver su cuota" forState: UIControlStateNormal];
        WEAKSELF
        [_btnLogin setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
            [NSObject clickFeedback];
            [weakSelf.btnLogin addClickAnimate];
            [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Register_Login action:KEY_BUTTON_CLICK type:KEY_button];
            [weakSelf requestIsNeedLoginAuth];
        }];
    }
    return _btnLogin;
}
- (NSString *)strAgreement{
    if (!_strAgreement) {
        _strAgreement = [NSString new];
        _strAgreement = @"El inicio de sesión en la cuenta implica su conformidad con el 《Acuerdo de Servicio al Usuario》 y la 《Política de Privacidad》";
    }
    return _strAgreement;
}
- (NSString *)strServicio{
    if (!_strServicio) {
        _strServicio = [NSString new];
        _strServicio = @"《Acuerdo de Servicio al Usuario》";
    }
    return _strServicio;
}
- (NSString *)strPrivacidad{
    if (!_strPrivacidad) {
        _strPrivacidad = [NSString new];
        _strPrivacidad = @"《Política de Privacidad》";
    }
    return _strPrivacidad;
}
- (UITextView *)labelAgreement
{
    if (_labelAgreement == nil) {
        _labelAgreement = [UITextView  new];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.strAgreement];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 2;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedString.length)];
        [attributedString addAttribute:NSLinkAttributeName
                                 value:@"servicio"
                                 range:[[attributedString string] rangeOfString:self.strServicio]];
        [attributedString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} range:[self.strAgreement rangeOfString:self.strServicio]];
        _labelAgreement.attributedText = attributedString;
        _labelAgreement.linkTextAttributes = @{NSForegroundColorAttributeName: COLOR_BLUE,
                                               NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
        [attributedString addAttribute:NSLinkAttributeName
                                 value:@"privacidad"
                                 range:[[attributedString string] rangeOfString:self.strPrivacidad]];
        [attributedString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} range:[self.strAgreement rangeOfString:self.strPrivacidad]];
        _labelAgreement.attributedText = attributedString;
        _labelAgreement.linkTextAttributes = @{NSForegroundColorAttributeName: COLOR_BLUE,
                                               NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
        UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, 0, 0);
        _labelAgreement.textContainerInset = insets;
        _labelAgreement.width = self.btnLogin.width;
        _labelAgreement.font = [UIFont systemFontOfSize:12];
        _labelAgreement.textAlignment = NSTextAlignmentLeft;
        [_labelAgreement sizeToFit];
        _labelAgreement.textColor = COLOR_LIGHT_GRAY;
        _labelAgreement.delegate = self;
        _labelAgreement.editable = NO;
        _labelAgreement.scrollEnabled = NO;
        _labelAgreement.leftTop = XY(self.btnLogin.left, self.btnLogin.bottom+18);
    }
    return  _labelAgreement;
}
- (WXPChooseSMSVerificWayView *)chooseSMSVerificWayView
{
    if (_chooseSMSVerificWayView == nil) {
        _chooseSMSVerificWayView = [WXPChooseSMSVerificWayView  new];
        WEAKSELF
        _chooseSMSVerificWayView.blockVoiceClick = ^{
             [GlobalMethod buryPointWithPageName:KEY_VCodeDialog featureName:KEY_Voice_Send action:KEY_BUTTON_CLICK type:KEY_button];
            [weakSelf requestSendVoice];
        };
        _chooseSMSVerificWayView.blockSmsClick = ^{
             [GlobalMethod buryPointWithPageName:KEY_VCodeDialog featureName:KEY_SMS_Send action:KEY_BUTTON_CLICK type:KEY_button];
            [weakSelf requestSendSms];
        };
    }
    return  _chooseSMSVerificWayView;
}
- (UpdatePopUpWindowView *)updatePromptView
{
    if (_updatePromptView == nil) {
        _updatePromptView = [UpdatePopUpWindowView  new];
    }
    return  _updatePromptView;
}
- (WXPAgreementDialogView *)viewAgreementDialog{
    if (!_viewAgreementDialog) {
        _viewAgreementDialog = [WXPAgreementDialogView new];
    }
    return _viewAgreementDialog;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear: animated];
    self.startTime = [GlobalMethod getTimeStampMillisecond];
    // 打点
    [self enterPageHitPoint];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [GlobalMethod getAdvertisingIdentifier];
    });
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestAppUpdateConfig];
    [self configUI];
}

#pragma mark - UI
- (void)configUI{
    [self.view addSubview:self.viewBg];
    [self.view addSubview:self.imageLogo];
    [self.view addSubview:self.imageBg];
    self.labelTitle.leftTop = XY(self.imageLogo.left, self.imageLogo.bottom+Ratio(18));
    [self.view addSubview:self.labelTitle];
    self.viewBack.height = SCREEN_HEIGHT-self.labelTitle.bottom-Ratio(35);
    self.viewBack.leftTop = XY(0, self.labelTitle.bottom+Ratio(35));
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.viewBack.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(40.0, 40.0)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = path.CGPath;
    self.viewBack.layer.mask = maskLayer;
    [self.view addSubview:self.viewBack];
    
    [self resetUIHiddenAudioSendHint:true];
    [self.viewBack addSubview:self.labelAudioSendHint];
    [self.viewBack addSubview:self.viewPhoneBack];
    [self.viewPhoneBack addSubview:self.labelPhoneArea];
    [self.viewPhoneBack addSubview:self.tfPhone];
    [self.viewBack addSubview:self.viewCodeBack];
    [self.viewCodeBack addSubview:self.btnCode];
    [self.viewCodeBack addSubview:self.labelTime];
    [self.viewCodeBack addSubview:self.tfCode];
    [self.viewBack addSubview:self.btnAudio];
    [self.viewBack addSubview:self.btnLogin];
    [self.viewBack addSubview:self.labelAgreement];
    [self.view addSubview:self.viewAgreementDialog];
}

- (void)resetUIHiddenAudioSendHint:(BOOL)isHidden{
    self.labelAudioSendHint.hidden = isHidden;
    self.labelAudioSendHint.leftTop = XY(30, Ratio(25));
    self.viewPhoneBack.centerXTop = XY(SCREEN_WIDTH/2, isHidden ? BUTTON_HEIGHT : self.labelAudioSendHint.bottom+Ratio(16));
    self.labelPhoneArea.leftCenterY = XY(6, self.viewPhoneBack.height/2);
    self.tfPhone.widthHeight = XY(self.viewPhoneBack.width-15-self.labelPhoneArea.right-15, self.viewPhoneBack.height-10);
    self.tfPhone.leftCenterY = XY(self.labelPhoneArea.right+15, self.viewPhoneBack.height/2);
    self.viewCodeBack.centerXTop = XY(SCREEN_WIDTH/2, self.viewPhoneBack.bottom+Ratio(20));
    self.labelTime.rightCenterY = XY(self.btnCode.right, self.viewCodeBack.height/2);
    self.tfCode.widthHeight = XY(self.btnCode.left-15-19, self.viewCodeBack.height-10);
    self.tfCode.leftCenterY = XY(19, self.viewCodeBack.height/2);
    self.btnAudio.leftTop = XY(30, self.viewCodeBack.bottom+1);
    self.btnLogin.centerXTop = XY(SCREEN_WIDTH/2, self.viewCodeBack.bottom+Ratio(70));
    self.labelAgreement.leftBottom = XY(self.btnLogin.left, self.viewBack.height-20);
}


#pragma mark - 点击
- (void)btnClick:(UIButton *)sender{
    [NSObject clickFeedback];
    [sender addClickAnimate];
    [self.view endEditing:true];
    switch (sender.tag) {
        case 2: // code
        {
            [self requestSendSmsCount];
        }
            break;
        case 3: // audio
        {
            [self requestSendVoice];
        }
            break;
        default:
            break;
    }
}

- (void)startCountdown{
    __block NSInteger timeOut = 59;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeOut <= 0) {
            // 结束
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.labelTime.hidden = true;
                self.btnCode.hidden = false;
                self.imageAudio.image = [UIImage imageNamed:@"icon-login-audio-click"];
                self.labelAudioTime.hidden = true;
                self.btnAudio.userInteractionEnabled = true;
                self.labelAudio.hidden = false;
                [self resetUIHiddenAudioSendHint:true];
            });
        } else {
            int seconds = timeOut % 60;
            NSString *timeStr = [NSString stringWithFormat:@"%0.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.labelTime fitTitle:[NSString stringWithFormat:@"%@s",timeStr] variable:0];
                self.labelTime.rightCenterY = XY(self.labelTime.right, self.labelTime.centerY);
                [self.labelAudioTime fitTitle:[NSString stringWithFormat:@"liamame %@s",timeStr] variable:0];
                self.labelAudioTime.leftCenterY = XY(self.labelAudioTime.left, self.labelAudioTime.centerY);
                self.btnAudio.width = self.labelAudioTime.right+6;
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - textField/textView
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView{
    [self.view endEditing:YES];
}
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
    [NSObject clickFeedback];
    NSRange rangeServicio = [self.strAgreement rangeOfString:self.strServicio];
    if (NSEqualRanges(characterRange, rangeServicio)) {
        [Global_Nav pushVCName:@"WXPRegisterAgreementVC" animated:true];
    }
    NSRange rangePrivacidad = [self.strAgreement rangeOfString:self.strPrivacidad];
    if (NSEqualRanges(characterRange, rangePrivacidad)) {
        [Global_Nav pushVCName:@"WXPPrivacyAgreementVC" animated:true];
    }
    return YES;
}
- (void)textFieldDidChange:(UITextField *)textField{
    if(textField == self.tfPhone){
        self.btnCode.userInteractionEnabled = isStr(self.tfPhone.text);
        [self.btnCode setTitleColor: isStr(self.tfPhone.text) ? COLOR_BLACK : COLOR_LIGHT_GRAY forState:UIControlStateNormal];
        if (self.labelAudioTime.hidden == true) {
            self.imageAudio.image = [UIImage imageNamed: isStr(self.tfPhone.text) ? @"icon-login-audio-click" : @"icon-login-audio-unclick"];
            self.btnAudio.userInteractionEnabled = isStr(self.tfPhone.text);
        }
        self.labelAudio.textColor = isStr(self.tfPhone.text) ? COLOR_BLACK : COLOR_LIGHT_GRAY;
    }
    self.btnLogin.userInteractionEnabled = isStr(self.tfPhone.text) && isStr(self.tfCode.text);
    [self.btnLogin setBackgroundColor: self.btnLogin.userInteractionEnabled ? COLOR_PRIMARY : [UIColor colorWithHexString:@"#F2F39C"]];
    [self.btnLogin setTitleColor:self.btnLogin.userInteractionEnabled ? COLOR_BLACK : [UIColor colorWithHexString:@"838380"] forState:UIControlStateNormal];
}

// 获得焦点
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if(textField == self.tfPhone){
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Phone_Focus extInfo:nil];
        [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Phone_Input action:KEY_GET_FOCUS type:KEY_input];
    }
    if(textField == self.tfCode){
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_VCode_Focus extInfo:nil];
        [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_VCode_Input action:KEY_GET_FOCUS type:KEY_input];
    }
}
// 失去焦点
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if(textField == self.tfPhone){
        [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Phone_Input action:KEY_LOST_FOCUS type:KEY_input];
    }
    if(textField == self.tfCode){
        [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_VCode_Input action:KEY_LOST_FOCUS type:KEY_input];
    }
}

// 粘贴行为
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(textField == self.tfPhone){
        if (isStr(string)) {
            // 打点
            [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Phone_Input extInfo:nil];
            [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Phone_Input action:KEY_INPUT type:KEY_input];
        }
    }
    if(textField == self.tfCode){
        if (isStr(string)) {
            // 打点
            // 即将输入的完整内容
            NSString * newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
            [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_VCode_Input extInfo:@{@"vcode": readStr(newText)}];
            [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_VCode_Input action:KEY_INPUT type:KEY_input];
        }
    }
    // 检测是否为粘贴行为
    NSString * trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([UIPasteboard generalPasteboard].string.length > 0 && [trimmedString isEqualToString:[UIPasteboard generalPasteboard].string]) {
        if(textField == self.tfPhone){
            [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Phone_Input action:KEY_PARSE type:KEY_input];
        }
        if(textField == self.tfCode){
            [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_VCode_Input action:KEY_PARSE type:KEY_input];
        }
        return true;
    }
    return YES;
}


#pragma mark - request
// 进入界面打点
- (void)enterPageHitPoint{
    if ([[GlobalMethod getDeviceNetworkType] isEqualToString:@"none"]) {
        // 未连接网络
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self enterPageHitPoint]; // 再次调用该方法
        });
        return;
    }
    [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Enter extInfo:nil];
}
// app软更信息
- (void)requestAppUpdateConfig{
    if ([[GlobalMethod getDeviceNetworkType] isEqualToString:@"none"]) {
        // 未连接网络
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self requestAppUpdateConfig];
        });
        return;
    }
    [RequestApi requestAppUpdateConfigWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        BOOL isShow = [response boolValueForKey:KEY_update];
        if (isShow) {
            ModelBtn * model = [ModelBtn new];
            model.content = [response stringValueForKey:KEY_updateRemark];
            model.title = [response stringValueForKey:KEY_updateUrl];
            model.isSelected = [response boolValueForKey:KEY_urlType];
            [self.updatePromptView resetViewWithModel:model];
            UIWindow * window = [UIApplication sharedApplication].windows.firstObject;
            [window endEditing:true];
            if([GlobalMethod readBoolLocal:LOCAL_HAVE_SHOW_APP_UPDATE] == false){
                // 还未显示过软更弹窗-弹窗显示
                [window addSubview:self.updatePromptView];
                [GlobalMethod writeBool:true local:LOCAL_HAVE_SHOW_APP_UPDATE];
            }
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

- (void)requestSendSmsCount{
    [RequestApi requestSendSmsCountWithPhone:self.tfPhone.text delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        NSString * numStr = [NSString stringWithFormat:@"%@",response];
        if([numStr integerValue] <= 3){
            // 次数 <= 3，调用发送短信接口
            [self requestSendSms];
        }else{
            [self showChooseSMSVerificWayView];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
- (void)showChooseSMSVerificWayView{
    UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
    self.chooseSMSVerificWayView.leftTop = XY(0, 0);
    [window addSubview:self.chooseSMSVerificWayView];
}

// 发送短信验证码
- (void)requestSendSms{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_SMS_Send_Click extInfo:@{@"phone": readStr(self.tfPhone.text)}];
    [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_SMS_Send action:KEY_BUTTON_CLICK type:KEY_button];
    [RequestApi requestSendSmsWithPhone:self.tfPhone.text type:KEY_login smsChannel:KEY_SMS delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_SMS_Send_Success extInfo:@{@"phone": readStr(self.tfPhone.text)}];
        // 验证码发送成功
        [GlobalMethod showAlert:@"Código de verificación por SMS obtenido con éxito"];
        [self showTimeCountdown:false];

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 发送语音验证码
- (void)requestSendVoice{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Voice_Send_Click extInfo:@{@"phone": readStr(self.tfPhone.text)}];
    [GlobalMethod buryPointWithPageName:KEY_Register featureName:KEY_Voice_Send action:KEY_BUTTON_CLICK type:KEY_button];
    [RequestApi requestSendSmsWithPhone:self.tfPhone.text type:KEY_login smsChannel:KEY_VOICE delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Voice_Send_Success extInfo:@{@"phone": readStr(self.tfPhone.text)}];
        // 验证码发送成功
        [GlobalMethod showAlert:@"Le llamaremos en 5 min para darle el código de verificación"];
        
        [self.labelAudioSendHint fitTitle:[NSString stringWithFormat:@"Código de verificación se llamará por teléfono a '+52-%@', por favor, mantenga su teléfono disponible.", self.tfPhone.text] variable:SCREEN_WIDTH-30-30];
        [self resetUIHiddenAudioSendHint:false];
        
        [self showTimeCountdown:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [self.chooseSMSVerificWayView removeFromSuperview];
    }];
}

- (void)showTimeCountdown:(BOOL)isAudio{
    [self.chooseSMSVerificWayView removeFromSuperview];
    self.btnCode.hidden = true;
    self.labelTime.hidden = false;
    self.btnAudio.userInteractionEnabled = false;
    self.imageAudio.image = isAudio ? [UIImage imageNamed:@"icon-login-audio-click"] : [UIImage imageNamed:@"icon-login-audio-unclick"];
    self.labelAudioTime.textColor = isAudio ? COLOR_BLACK : COLOR_LIGHT_GRAY;
    self.labelAudio.hidden = true;
    self.labelAudioTime.hidden = false;
    [self startCountdown];
}

// 是否需要活体登录
- (void)requestIsNeedLoginAuth{
    [RequestApi requestNeedLoginAuthWithPhone:[self.tfPhone.text removeHeadAndTailSpace] vcode:[self.tfCode.text removeHeadAndTailSpace] delegate:self success:^(id _Nonnull response, id  _Nonnull mark) {
        
        BOOL needLoginAuth = false;
        if ([response isKindOfClass:[NSNumber class]]) {
            needLoginAuth = [response boolValue];
        }
        if (needLoginAuth == true) {
            // 登录活体
            WXPLoginAuthVC * vc = [WXPLoginAuthVC new];
            vc.phone = [self.tfPhone.text removeHeadAndTailSpace];
            vc.code = [self.tfCode.text removeHeadAndTailSpace];
            //WEAKSELF
            vc.blockAddTracking = ^{
                // [weakSelf requestAddRiskControlTracking];
            };
            [Global_Nav pushViewController:vc animated:true];
        } else {
            // 登录
            [self requestLogin];
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 登录
- (void)requestLogin{
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_Register action:KEY_Click extInfo:@{@"vcode": readStr(self.tfCode.text)}];
    [RequestApi requestLoginWithPhone:[self.tfPhone.text removeHeadAndTailSpace] vcode:[self.tfCode.text removeHeadAndTailSpace] livenChannelEnum:KEY_SILENCE_LIVENESS delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod addRiskControlWithType:KEY_REGISTERED startTime:@"" endTime:[GlobalMethod getTimeStampMillisecond]];
        [Global_Nav popToRootViewControllerAnimated:YES];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {

    }];
}




@end
